import cv2
import os

# ----------------------------------------------------------------------
# 读取文件路径
path = "img"
# 保存文件路径
path1 = 'imgs'
# 缩放大小设置
re = (500, 500)

if not os.path.exists(path1):
    os.mkdir(path1)

for i in os.listdir(path):
    img_origin = cv2.imread(os.path.join(path, i))

    r_image = cv2.resize(img_origin, re)
    # # 灰度图
    image = cv2.cvtColor(r_image, cv2.COLOR_BGR2GRAY)
    # print(image.shape)

    # print(image.shape)
    # 保存图像
    cv2.imwrite(os.path.join(path1, i), image)

# ----------------------------------------------------------------------

# def cv_show(neme, img):
#     cv2.namedWindow(neme, cv2.WINDOW_NORMAL)
#     cv2.imshow(neme, img)
#     cv2.waitKey(0)
#     cv2.destroyAllWindows()


# ----------------------------------------------------------------------

import base64
import json
import os
import numpy as np
from PIL import Image
from labelme import utils
from skimage import img_as_ubyte


def hacker(img):
    # 二分类，二值化不是0与255，而是0与1
    img = np.clip(img[:], 0, 1)
    return img


# 读取文件路径
json_file = "mask"
# 保存文件路径
path1 = 'masks'
# 缩放大小设置
re = (500, 500)

if not os.path.exists(path1):
    os.mkdir(path1)

list_path = os.listdir(json_file)

for i in range(0, len(list_path)):
    path = os.path.join(json_file, list_path[i])
    if os.path.isfile(path) & path.endswith('.json'):

        data = json.load(open(path))
        imageData = data.get('imageData')
        if not imageData:
            imagePath = os.path.join(os.path.dirname(json_file), data['imagePath'])
            with open(imagePath, 'rb') as f:
                imageData = f.read()
                imageData = base64.b64encode(imageData).decode('utf-8')

        img = utils.img_b64_to_arr(imageData)  # 原始图像

        label_name_to_value = {'_background_': 0}
        for shape in sorted(data['shapes'], key=lambda x: x['label']):
            label_name = shape['label']
            if label_name in label_name_to_value:
                label_value = label_name_to_value[label_name]
            else:
                label_value = len(label_name_to_value)
                label_name_to_value[label_name] = label_value

        lbl, _ = utils.shapes_to_label(img.shape, data['shapes'], label_name_to_value)

        # mask_dir = osp.join(osp.dirname(json_file), path1)
        # 在桌面生成mask.png的文件夹
        # if not osp.exists(mask_dir):
        #     os.mkdir(mask_dir)

        mask_dst = img_as_ubyte(lbl)
        out_img = Image.fromarray(np.uint8(mask_dst) * 255)

        img_ = np.array(out_img)
        # cv_show('neme', img_)
        # exit()

        # img_name, _ = list_path[i].split(".")
        # out_img.save(mask_dir + '/' + img_name + '_mask.jpg')

        image_hui = cv2.resize(img_, re)

        # 图像内只有0 1
        img_mask = hacker(image_hui)

        # # 保存图像
        img_name, _ = list_path[i].split(".")
        cv2.imwrite(path1 + '/' + img_name + '_mask.jpg', img_mask)

